package com.fubowen.reader.adapter

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fubowen.reader.db.ThemeDatabase
import com.fubowen.reader.db.model.BookCatalog
import com.fubowen.reader.db.model.BookChapter
import com.fubowen.reader.db.model.toBookChapter

class BookCatalogPagingSource(private val bookId: Int, val database: ThemeDatabase) : PagingSource<Int, BookCatalog>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, BookCatalog> {
        return try {

            val pageIndex = params.key ?: 1
            val takeCount = params.loadSize
            val skipCount = (pageIndex - 1) * takeCount
            val list = database.bookDao().getPageCatalog(bookId, takeCount, skipCount)
            LoadResult.Page(
                data = list,
                prevKey = if (pageIndex == 1) null else pageIndex.minus(1),
                nextKey = if (list.isEmpty()) null else pageIndex.plus(1)
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, BookCatalog>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }
}